<template>
  <div class="TUIChat" :class="[!isPC ? 'TUIChat-H5' : '']">
    <div class="TUIChat-main" v-if="messageList.length">
      <!-- <div class="TUIChat-safe-tips">
        <span>
          {{
            TUITranslateService.t(
              "TUIChat.【安全提示】本 APP 仅用于体验腾讯云即时通信 IM 产品功能，不可用于业务洽谈与拓展。请勿轻信汇款、中奖等涉及钱款的信息，勿轻易拨打陌生电话，谨防上当受骗。"
            )
          }}
        </span>
        <a @click="openComplaintLink(Link.complaint)">{{
          TUITranslateService.t("TUIChat.点此投诉")
        }}</a>
      </div> -->
      <div
        class="TUIChat-application-tips"
        v-if="isGroup && groupApplicationCount > 0"
        @click="toggleApplicationList()"
      >
        <span
          >{{ groupApplicationCount }}
          {{ TUITranslateService.t("TUIChat.条入群申请") }}
          <span class="application-tips-btn">{{
            TUITranslateService.t("TUIChat.点击处理")
          }}</span>
        </span>
      </div>
      <scroll-view
        class="TUI-message-list"
        scroll-y="true"
        :scroll-top="scrollTop"
      >
        <p
          class="message-more"
          @click="getHistoryMessageList"
          v-if="!isCompleted"
        >
          {{ TUITranslateService.t("TUIChat.查看更多") }}
        </p>
        <li
          v-for="(item, index) in messageList"
          :key="item.vueForRenderKey"
          :id="item.ID"
          ref="messageAimID"
          class="message-li"
        >
          <MessageTimestamp
            :currTime="item.time"
            :prevTime="index > 0 ? messageList[index - 1].time : 0"
          ></MessageTimestamp>
		  
          <div 
            class="message-item"
            @click.stop="toggleID = ''"
          >
			<view class="sys_msg_box" v-if="item.conversationID == 'C2Chudongmsg' ||item.conversationID == 'C2Cadministrator' ||item.conversationID == 'C2Csysmsg' || item.left_1">
				<view class="sys_msg_item">
					<view class="sys_tit display-flex just-between">
						<text class="">{{item.title || item.payload.text}}</text>
						<!-- <image src="https://cdnauth.dreamyuewen.com/images/bao.png" class="jubox" mode="aspectFit" @tap="currentId=item.ID,show=true"></image> -->
					</view>
					<view class="sys_line display-flex" v-if="item.left_1">
						<text class="sys_label">{{item.left_1}}</text>
						<text class="sys_cont">{{item.left_1_val}}</text>
					</view>
					<view class="sys_line display-flex" v-if="item.left_2">
						<text class="sys_label">{{item.left_2}}</text>
						<text class="sys_cont">{{item.left_2_val}}</text>
					</view>
					<view class="sys_line display-flex" v-if="item.left_3">
						<text class="sys_label">{{item.left_3}}</text>
						<text class="sys_cont">{{item.left_3_val}}</text>
					</view>
					<view class="sys_line display-flex" v-if="item.left_4">
						<text class="sys_label">{{item.left_4}}</text>
						<text class="sys_cont">{{item.left_4_val}}</text>
					</view>
					<view class="sys_line display-flex" v-if="item.left_5">
						<text class="sys_label">{{item.left_5}}</text>
						<text class="sys_cont">{{item.left_5_val}}</text>
					</view>
					  
					<view class="sys_detail display-flex just-between" @tap="gotoDetail(item)" v-if="item.types && item.types != 888">
						<text>查看详情</text>
						<image src="https://cdnauth.dreamyuewen.com/images/msg_r.png" class="rar" mode=""></image>
					</view>
				</view>
			</view>
		  
            <block v-else>
				<MessageTip
				  v-if="
				    item.type === TYPES.MSG_GRP_TIP ||
				    isCreateGroupCustomMessage(item)
				  "
				  :content="item.getMessageContent()"
				/>
				<div
				  v-else-if="!item.isRevoked && !item.getSignalingInfo()"
				  @longpress="handleToggleMessageItem($event, item, index, true)"
				  @touchstart="handleH5LongPress($event, item, index, 'touchstart')"
				  @touchend="handleH5LongPress($event, item, index, 'touchend')"
				  @mouseover="handleH5LongPress($event, item, index, 'touchend')"
				>
				  <MessageBubble
				    :messageItem="item"
				    :content="item.getMessageContent()"
				    @resendMessage="resendMessage(item)"
				  >
				    <MessageText
				      v-if="item.type === TYPES.MSG_TEXT"
				      :content="item.getMessageContent()"
				    />
				    <ProgressMessage
				      v-if="item.type === TYPES.MSG_IMAGE"
				      :content="item.getMessageContent()"
				      :messageItem="item"
				    >
				      <MessageImage
				        :content="item.getMessageContent()"
				        :messageItem="item"
				        @previewImage="handleImagePreview"
				      />
				    </ProgressMessage>
				    <MessageVideo
				      v-if="item.type === TYPES.MSG_VIDEO"
				      :content="item.getMessageContent()"
				      :messageItem="item"
				      :isPC="isPC"
				    />
				    <MessageAudio
				      v-if="item.type === TYPES.MSG_AUDIO"
				      :content="item.getMessageContent()"
				      :messageItem="item"
				    />
				    <MessageFile
				      v-if="item.type === TYPES.MSG_FILE"
				      :content="item.getMessageContent()"
				    />
				    <MessageFace
				      v-if="item.type === TYPES.MSG_FACE"
				      :content="item.getMessageContent()"
				      :isPC="isPC"
				    />
				    <MessageLocation
				      v-if="item.type === TYPES.MSG_LOCATION"
				      :content="item.getMessageContent()"
				    />
				    <MessageCustom
				      v-if="item.type === TYPES.MSG_CUSTOM"
				      :content="item.getMessageContent()"
				      :messageItem="item"
				    />
				  </MessageBubble>
				</div>
				<MessagePlugin
				  v-else-if="!item.isRevoked && item.getSignalingInfo()"
				  :message="item"
				  @resendMessage="resendMessage"
				  @handleToggleMessageItem="handleToggleMessageItem"
				  @handleH5LongPress="handleH5LongPress"
				/>
				<MessageRevoked
				  v-else
				  :isEdit="item.type === TYPES.MSG_TEXT"
				  :messageItem="item"
				  @messageEdit="handleEdit(item)"
				/>
				<MessageTool
				  :class="[
				    'message-tool',
				    item.flow === 'out' ? 'message-tool-out' : 'message-tool-in',
				  ]"
				  :messageItem="item"
				  v-if="item.ID === toggleID"
				/>
			</block>
          </div>
        </li>
      </scroll-view>
      <Dialog
        v-if="reSendDialogShow"
        :show="reSendDialogShow"
        :isH5="!isPC"
        :center="true"
        :isHeaderShow="isPC"
        @submit="resendMessageConfirm()"
        @update:show="(e) => (reSendDialogShow = e)"
      >
        <p class="delDialog-title">
          {{ TUITranslateService.t("TUIChat.确认重发该消息？") }}
        </p>
      </Dialog>
      <ImagePreviewer
        v-if="showImagePreview"
        :currentImage="currentImagePreview"
        :imageList="imageMessageList"
        @close="onImagePreviewerClose"
      ></ImagePreviewer>
      <MessageGroupSystem
        v-if="showGroupApplication"
        :groupID="groupID"
        @toggleApplicationList="toggleApplicationList"
        @handleGroupApplication="handleGroupApplication"
      ></MessageGroupSystem>
    </div>
	
	<view class="empytView" v-if="!messageList.length">
		<image :src="'/images/kong.png' | formatImgUrl" mode="widthFix" />
	</view>
	<view class="zhezhao" v-if="show">
		
	</view>
	<view class="mask3" v-if="show">
		<view class="matop" @click.stop="is_tops(0)">
			<view class="matxt">
				<text>删除</text>
			</view>
			<image :src="'/images/rarr.png'  | formatImgUrl" class="mapic" mode=""></image>
		</view>
		<view class="qubox" @click.stop="show = false">
			取消
		</view>
	</view>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, onUnmounted } from "../../../adapter-vue";
import TUIChatEngine, {
  TUIGlobal,
  IMessageModel,
  TUIStore,
  StoreName,
  TUITranslateService,
  TUIChatService,
  TUIGroupService,
} from "@tencentcloud/chat-uikit-engine";

import Link from "./link";
import MessageText from "./message-elements/message-text.vue";
import ProgressMessage from "../../common/ProgressMessage/index.vue";
import MessageImage from "./message-elements/message-image.vue";
import MessageAudio from "./message-elements/message-audio.vue";
import MessageFile from "./message-elements/message-file.vue";
import MessageFace from "./message-elements/message-face.vue";
import MessageCustom from "./message-elements/message-custom.vue";
import MessageTip from "./message-elements/message-tip.vue";
import MessageBubble from "./message-elements/message-bubble.vue";
import MessageLocation from "./message-elements/message-location.vue";
import MessageTimestamp from "./message-elements/message-timestamp.vue";
import MessageVideo from "./message-elements/message-video.vue";
import MessageTool from "./message-tool/index.vue";
import MessageRevoked from "./message-tool/message-revoked.vue";
import MessageGroupSystem from "./message-elements/message-group-system.vue";
import MessagePlugin from "../../../plugins/plugin-components/message-plugin.vue";

import Dialog from "../../common/Dialog/index.vue";
import ImagePreviewer from "../../common/ImagePreviewer/index.vue";
import { isCreateGroupCustomMessage } from "../utils/utils";

const props = defineProps({
  groupID: {
    type: String,
    default: "",
  },
  isGroup: {
    type: Boolean,
    default: false,
  }, 
  show:{
	type: Boolean,
	default: false,
  }
});
const isPC = ref(TUIGlobal.getPlatform() === "pc");
const isH5 = ref(TUIGlobal.getPlatform() === "h5");
const messageListRef = ref();
const title = ref("TUIChat");
const messageList = ref();
const isCompleted = ref(false);
const currentConversationID = ref("");
const nextReqMessageID = ref();
const toggleID = ref("");
const scrollTop = ref(5000); // 首次是 15 条消息，最大消息高度为300
const TYPES = ref(TUIChatEngine.TYPES);
const listRef = ref();
const isLoadMessage = ref(false);
const isLongpressing = ref(false);

// 加群申请系统消息
const groupApplicationCount = ref(0);
const showGroupApplication = ref(false);
const applicationUserIDList = ref([]);

// 消息重发 Dialog
const reSendDialogShow = ref(false);
const resendMessageData = ref();
const emits = defineEmits(["handleEditor"]);

// 图片预览相关
const showImagePreview = ref(false);
const currentImagePreview = ref<typeof IMessageModel>();
const imageMessageList = computed(() =>
  messageList?.value?.filter((item: typeof IMessageModel) => {
    return !item.isRevoked && item.type === TYPES.value.MSG_IMAGE;
  })
);

// 消息滑动到底部，建议搭配 nextTick 使用
const scrollToBottom = () => {
  // 文本消息高度：60, 最大消息高度 280
  scrollTop.value += 300;
  // 解决 uniapp 打包到 app 首次进入滑动到底部，300 可设置
  const timer = setTimeout(() => {
    scrollTop.value += 1;
    clearTimeout(timer);
  }, 300);
};

// 监听回调函数
const onCurrentConversationIDUpdated = (conversationID: string) => {
  currentConversationID.value = conversationID;
  TUIGroupService.getGroupApplicationList().then((res: any) => {
    const applicationList = res.data.applicationList.filter(
      (application: any) => application.groupID === props.groupID
    );
    applicationUserIDList.value = applicationList.map((application: any) => {
      return application.applicationType === 0
        ? application.applicant
        : application.userID;
    });
    TUIStore.update(
      StoreName.CUSTOM,
      "groupApplicationCount",
      applicationList.length
    );
  });
};

// operationType 操作类型 1: 有用户申请加群   23: 普通群成员邀请用户进群
const onGroupSystemNoticeList = (list: Array<typeof IMessageModel>) => {
  const systemNoticeList = list.filter((message) => {
    const { operationType } = message.payload;
    return (
      (operationType === 1 || operationType === 23) &&
      message.to === props.groupID
    );
  });

  systemNoticeList.forEach((systemNotice) => {
    const { operationType } = systemNotice.payload;
    if (operationType === 1) {
      const { operatorID } = systemNotice.payload;
      if (!applicationUserIDList.value.includes(operatorID)) {
        applicationUserIDList.value.push(operatorID);
      }
    }
    if (operationType === 23) {
      const { inviteeList } = systemNotice.payload;
      inviteeList.forEach((invitee) => {
        if (!applicationUserIDList.value.includes(invitee)) {
          applicationUserIDList.value.push(invitee);
        }
      });
    }
  });
  const applicationCount = applicationUserIDList.value.length;
  TUIStore.update(StoreName.CUSTOM, "groupApplicationCount", applicationCount);
};

// 消息列表监听
TUIStore.watch(StoreName.CHAT, {
  messageList: (list: Array<typeof IMessageModel>) => {
    messageList.value = list
      .filter(message => !message.isDeleted)
      .map((message) => {
        message.vueForRenderKey = `${message.ID}`;
		
		if (message.payload.text && message.payload.text.indexOf('type') > -1) {
			let msgParse = JSON.parse(message.payload.text.substr(4))
			console.log(msgParse)
			message.title = msgParse.title
			message.id = msgParse.aid
			message.pid = msgParse.pid
			message.types = msgParse.type
			message.path = msgParse.path
			message.uid = msgParse.uid
			
			message.left_1 = msgParse.left_1
			message.left_1_val = msgParse.left_1_val
			message.left_2 = msgParse.left_2
			message.left_2_val = msgParse.left_2_val
			
			message.left_3 = msgParse.left_3
			message.left_3_val = msgParse.left_3_val
			message.left_4 = msgParse.left_4
			message.left_4_val = msgParse.left_4_val
			message.left_5 = msgParse.left_5
			message.left_5_val = msgParse.left_5_val
		}
		
        return message;
      });
    // 点击加载更多的消息不需要滑动到底部
    if (!isLoadMessage.value) {
      scrollToBottom();
    }
	
	console.log(list,'messageList',111);
  },
  isCompleted: (flag: boolean) => {
    isCompleted.value = flag;
  },
});

TUIStore.watch(StoreName.CONV, {
  currentConversationID: onCurrentConversationIDUpdated,
});

// 群系统消息
TUIStore.watch(StoreName.GRP, {
  groupSystemNoticeList: onGroupSystemNoticeList,
});

// 群系统消息数量
TUIStore.watch(StoreName.CUSTOM, {
  groupApplicationCount: (count: Number) => {
    groupApplicationCount.value = count;
  },
});

// 取消监听
onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversationID: onCurrentConversationIDUpdated,
  });
  // 群系统消息
  TUIStore.unwatch(StoreName.GRP, {
    groupSystemNoticeList: onGroupSystemNoticeList,
  });
});

// 获取历史消息
const getHistoryMessageList = () => {
  isLoadMessage.value = true;
  TUIChatService.getMessageList().then((res: any) => {
    const { nextReqMessageID: ID } = res.data;
    nextReqMessageID.value = ID;
    isLoadMessage.value = false;
  });
};

const toggleApplicationList = () => {
  showGroupApplication.value = !showGroupApplication.value;
};

const handleGroupApplication = (userID: string) => {
  const index = applicationUserIDList.value.indexOf(userID);
  if (index !== -1) {
    applicationUserIDList.value.splice(index, 1);
  }
};
// todo: webview 跳转
const openComplaintLink = (type: any) => {};

// 消息操作
const handleToggleMessageItem = (
  e: any,
  message: typeof IMessageModel,
  index: number,
  isLongpress = false
) => {
  if (isLongpress) {
    isLongpressing.value = true;
  }
  toggleID.value = message.ID;
};

// h5 long press
let timer: number;
const handleH5LongPress = (
  e: any,
  message: typeof IMessageModel,
  index: number,
  type: string
) => {
  if (!isH5.value) return;
  function longPressHandler() {
    clearTimeout(timer);
    handleToggleMessageItem(e, message, index, true);
  }
  function touchStartHandler() {
    timer = setTimeout(longPressHandler, 500);
  }
  function touchEndHandler() {
    clearTimeout(timer);
  }
  switch (type) {
    case "touchstart":
      touchStartHandler();
      break;
    case "touchend":
      touchEndHandler();
      setTimeout(() => {
        isLongpressing.value = false;
      }, 200);
      break;
  }
};

// 消息撤回后，编辑消息
const handleEdit = (message: typeof IMessageModel) => {
  emits("handleEditor", message, "reedit");
};

// 重发消息
const resendMessage = (message: typeof IMessageModel) => {
  reSendDialogShow.value = true;
  resendMessageData.value = message;
};

// 图片预览
// 开启图片预览
const handleImagePreview = (message: typeof IMessageModel) => {
  if (
    showImagePreview.value ||
    currentImagePreview.value ||
    isLongpressing.value
  ) {
    return;
  }
  showImagePreview.value = true;
  currentImagePreview.value = message;
};
// 关闭图片预览
const onImagePreviewerClose = () => {
  showImagePreview.value = false;
  setTimeout(() => {
    currentImagePreview.value = null;
  }, 50);
};

const resendMessageConfirm = () => {
  reSendDialogShow.value = !reSendDialogShow.value;
  const messageModel = resendMessageData.value;
  messageModel.resendMessage();
};

const gotoDetail = (item) => {
  console.log('gotoDetail',item,1111);
  
  let url;
  // 0回复发布的内容 2内容点赞 3评价的点赞
  if (item.types == 0 || item.types == 2 || item.types == 3) {
  	url = '/pages/find/content?id=' + item.id
  	// 1回复评价
  } else if (item.types == 1) {
  	url = '/pages/find/review?id=' + item.id + '&pid=' + item.pid
  	// 4开通VIP服务开通成功通知
  } else if (item.types == 4) {
  	url = '/pages/user/vip'
  	// 5您的需求已匹配成功 6您已收到新的订单
  } else if (item.types == 5 || item.types == 6) {
  	url = '/task/list/my_orderlist'
  	// 9您的入团申请已通过 10您的入团申请未通过
  } else if (item.types == 9 || item.types == 10) {
  	url = '/pages/user/success?id=' + item.id
  	// 14您的开票申请已通过
  } else if (item.types == 14) {
  	url = '/showcase/showcase/invoiceDetail?id=' + item.id
  	// 15您的橱窗申请已通过 16您的橱窗申请未通过
  } else if (item.types == 15 || item.types == 16) {
  	url = '/showcase/showcase/showcase'
  	// 17您的橱窗被被投诉下架，请从新提交审核
  } else if (item.types == 17) {
  	url = '/showcase/showcase/edit?id=' + item.id
	// 升级的提醒
  } else if (item.types == 19) {
  	url = '/pages/user/grade?uid=' + item.uid
	// 佣金申请提现 -- 佣金兑换粮币
  } else if (item.types == 20) {
  	url = '/pages/user/coin?type=2'
	// 你的个人认证已成功
  } else if (item.types == 21) {
  	url = '/pages/user/auth1'
	// 发票
  }else if (item.types == 22) {
  	url = '/showcase/showcase/invoice'
	// 粮币充值
  }else if (item.types == 24) {
  	url = '/pages/user/coin?type=1'
	// 提现
  }else if (item.types == 25) {
  	url = '/pages/user/withdrawal'
	// 平台协议修改通知 实名认证后台通知
  }else if (item.types == 18) {
  	url = item.path
  }
  
  if(!url){
	  return
  }
  uni.navigateTo({
	  url: url
  })
};

let currentId= ''
const is_tops = ()=>{
	let id = currentId
	let promise = IMessageModel.deleteMessage([id]);
	 promise.catch((error) => {
	   // 调用异常时业务侧可以通过 promise.catch 捕获异常进行错误处理
	 });
}
</script>
<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss">
	.zhezhao {
		height: 100vh;
		position: fixed;
		top: 0rpx;
		right: 0px;
		width: 100%;
		z-index: 101;
		background: rgba(51, 51, 51, 0.6);
	}
	
	.mask3 {
		position: fixed;
		width: 100%;
		text-align: center;
		margin: 0 auto;
		bottom: 0;
		z-index: 102;
		background: #F2F5F2;
		border-top-left-radius: 8px;
		border-top-right-radius: 8px;
		
		.matop {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx 68rpx;
			margin-bottom: 20rpx;
			border-bottom: 1px solid rgba(153, 153, 153, 0.1);
			background-color: #ffffff;
		
			.mapic {
				width: 40rpx;
				height: 40rpx;
				flex-shrink: 0;
			}
		
			.matxt {
				font-size: 28rpx;
				padding: 0 16rpx;
				font-weight: bold;
				letter-spacing: 0em;
				color: #3D3D3D;
			}
		}
		
		.qubox {
			line-height: 120rpx;
			text-align: center;
			font-size: 28rpx;
			font-weight: bold;
			letter-spacing: 0em;
			color: #3D3D3D;
			height: 120rpx;
			opacity: 1;
			background: #FFFFFF;
		}
	}
	
	.sys_msg_box {
		position: relative;
		// margin-top: -25rpx;
	
		.sys_msg_time {
			font-family: Source Han Sans CN;
			font-size: 10px;
			color: #999999;
			text-align: center;
			padding-bottom: 20rpx;
		}
	
		.sys_line {
			padding-bottom: 15rpx;
		}
	
		.sys_msg_item {
			padding: 0 30rpx;
			background-color: #fff;
			border-radius: 8px;
			font-family: Source Han Sans CN;
			font-size: 12px;
			color: #3D3D3D;
		}
	
		.sys_tit {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			padding-top: 32rpx;
			padding-bottom: 30rpx;
			font-family: Source Han Sans CN;
			font-size: 14px;
			font-weight: bold;
			color: #3D3D3D;
	
			text {
				width: 100%;
				// white-space: nowrap;
				// overflow: hidden;
				// text-overflow: ellipsis;
				word-break: break-all;
			}
		}
	
		.jubox {
			width: 32rpx;
			height: 32rpx;
		}
	
		.sys_label {
			font-family: Source Han Sans CN;
			font-size: 12px;
			color: #999999;
			white-space: nowrap;
		}
	
		.sys_cont {
			width: 80%;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
	
		}
	
		.sys_detail {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			padding: 32rpx 0;
			padding-top: 10rpx;
			font-family: Source Han Sans CN;
			font-size: 14px;
			font-weight: bold;
			color: #3D3D3D;
	
			image {
				width: 32rpx;
				height: 32rpx;
			}
		}
	}
</style>